/*
 * 组件注释
 * @Author: machinist_wq
 * @Date: 2022-05-03 12:50:21
 * @LastEditors: machinist_wq
 * @LastEditTime: 2022-09-02 23:19:20
 * @Description: 上传组件
 */
import { useState, useRef, forwardRef, useImperativeHandle } from "react";
import { Upload } from "antd";
import { CloudUploadOutlined } from "@ant-design/icons";

const { Dragger } = Upload;
const Index = forwardRef((props, ref) => {
  const {
    disabled = false,
    /* 是否可预览 */
    previewZoom,
    maxCount = 1,
    action = window.getUrlHref() + "/api/zjkc/file/uploadFile",
    accept = "image/*,.pdf,.png,.jpg",
    children,
    fileList,
    /* 上传以后的回调 */
    ...otherConfig
  } = props;

  const upDataRef = useRef(null);

  const [_props, set_props] = useState({
    fileList,
    action,
    disabled: disabled,
    accept,
    maxCount,
    multiple: false,
    showUploadList: true,
    ...otherConfig,
  });

  useImperativeHandle(ref, () => ({
    set_props,
    ...(upDataRef?.current ?? {}),
  }));

  const isDisabled =
    maxCount && maxCount <= upDataRef?.current?.fileList?.length;

  return window.isEmpty(children) ? (
    <Dragger
      ref={upDataRef}
      {..._props}
      style={{ borderRadius: 5 }}
      {...(disabled || isDisabled ? { disabled: true } : {})}>
      <React.Fragment>
        <p className="ant-upload-drag-icon">
          <CloudUploadOutlined style={{ color: "rgba(0,0,0,.5)" }} />
        </p>
        <p className="ant-upload-text">
          将文件拖拽到此处，或{" "}
          <a
            style={{
              ...(disabled || isDisabled
                ? { cursor: "not-allowed", color: "rgba(0, 0, 0, .25)" }
                : {}),
            }}>
            点击上传
          </a>
        </p>
      </React.Fragment>
    </Dragger>
  ) : (
    <Upload {..._props} ref={upDataRef} style={{ borderRadius: 5 }}>
      {_props.listType === "text"
        ? React.isValidElement(children)
          ? React.cloneElement(children, { disabled })
          : children
        : isDisabled
        ? React.isValidElement(children)
          ? React.cloneElement(children, { disabled: true })
          : children
        : React.isValidElement(children)
        ? React.cloneElement(children, { disabled })
        : children}
    </Upload>
  );
});
export default Index;
